const financeExport = require('../../../utils/finance-export')

Page({
  data: {
    exportList: [],
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    refreshing: false,
    // 类型和状态映射
    typeMap: {
      search: { text: '搜索结果', icon: '/assets/finance/finance-sys-search.svg' },
      month: { text: '月账单', icon: '/assets/finance/finance-sys-month.svg' },
      year: { text: '年账单', icon: '/assets/finance/finance-sys-year.svg' },
      // ...可扩展
    },
    statusMap: {
      wait_parse: '待处理',
      wait_download: '待下载',
      download: '已下载',
      error: '异常',
    },
  },
  onLoad() {
    this.loadList(true);
  },
  // 下拉刷新
  onRefresh() {
    if (this.data.loading) return;
    this.setData({ pageNum: 1, refreshing: true }, () => {
      this.loadList(true);
    });
  },
  // 上拉加载
  onLoadMore() {
    console.log('onLoadMore triggered', {
      loading: this.data.loading,
      hasMore: this.data.hasMore,
      pageNum: this.data.pageNum
    });
    if (this.data.loading || !this.data.hasMore) return;
    const nextPage = this.data.pageNum + 1;
    console.log('Loading next page:', nextPage);
    this.setData({ pageNum: nextPage }, () => {
      this.loadList(false);
    });
  },
  
  // 滚动到底部事件
  onScrollToLower(e) {
    this.onLoadMore();
  },
  // 文件大小转换
  formatFileSize(bytes) {
    if (!bytes || bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  },
  // 时间格式化
  formatTime(timeStr) {
    if (!timeStr) return '';
    try {
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      
      // 如果是今天
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      // 如果是昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      // 其他日期
      return date.toLocaleDateString('zh-CN', { 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit', 
        minute: '2-digit' 
      });
    } catch (e) {
      return timeStr;
    }
  },
  // 加载导出记录
  async loadList(reset = false) {
    if (reset) {
      this.setData({ pageNum: 1 });
    }
    console.log('loadList called', {
      reset,
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    });
    this.setData({ loading: true });
    try {
      const res = await financeExport.exportPageList({
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
      });
      
      let list = res.records || [];
      console.log('API response', {
        total: res.total,
        recordsLength: list.length,
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      });
      // 处理数据
      list = list.map(item => ({
        ...item,
        typeText: this.data.typeMap[item.type]?.text || item.type,
        typeIcon: this.data.typeMap[item.type]?.icon || '/assets/finance/finance-sys-other.svg',
        statusText: this.data.statusMap[item.state] || item.state,
        fileSizeText: item.fileSize ? this.formatFileSize(item.fileSize) : '',
        // 格式化时间
        createTimeText: this.formatTime(item.createTime),
        parseTimeText: this.formatTime(item.parseTime),
        parseFinishTimeText: this.formatTime(item.parseFinishTime),
        // 判断是否显示文件相关信息
        showFileInfo: item.state === 'wait_download' || item.state === 'download',
        // 判断是否显示错误信息
        showError: item.state === 'error' && item.errorMsg,
        // 判断是否为待处理状态（简化布局）
        isWaitParse: item.state === 'wait_parse',
        // 判断是否为错误状态（需要显示错误信息）
        isError: item.state === 'error',
        // 判断是否为可下载状态（显示文件信息和操作按钮）
        isDownloadable: item.state === 'wait_download' || item.state === 'download',
      }));
      
      // 计算是否还有更多数据
      let hasMore = false;
      if (res.total !== undefined && res.total !== null) {
        // 如果有总数，根据总数判断
        hasMore = (this.data.pageNum - 1) * this.data.pageSize + list.length < res.total;
      } else {
        // 如果没有总数，根据当前页数据量判断
        hasMore = list.length === this.data.pageSize;
      }
      
      this.setData({
        exportList: reset ? list : this.data.exportList.concat(list),
        hasMore: hasMore,
        loading: false,
        refreshing: false,
      });
    } catch (error) {
      console.error('加载导出记录失败:', error);
      this.setData({ loading: false, refreshing: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },
  // 下载文件
  onDownload(e) {
    const item = e.currentTarget.dataset.item;
    if (!item.fileUrl) return wx.showToast({ title: '无下载链接', icon: 'none' });
    
    wx.showLoading({ title: '下载中...', mask: true });
    
    wx.downloadFile({
      url: item.fileUrl,
      success: res => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          // 保存文件到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: saveRes => {
              wx.showModal({
                title: '下载成功',
                content: 'Excel文件已保存到本地，是否打开？',
                confirmText: '打开',
                cancelText: '取消',
                success: modalRes => {
                  if (modalRes.confirm) {
                    // 打开文件
                    wx.openDocument({
                      filePath: saveRes.savedFilePath,
                      fileType: 'xlsx',
                      success: () => {
                        console.log('文件打开成功');
                      },
                      fail: error => {
                        console.error('文件打开失败:', error);
                        wx.showToast({ title: '文件打开失败', icon: 'none' });
                      }
                    });
                  }
                }
              });
            },
            fail: error => {
              console.error('文件保存失败:', error);
              wx.showToast({ title: '文件保存失败', icon: 'none' });
            }
          });
        } else {
          wx.showToast({ title: '下载失败', icon: 'none' });
        }
      },
      fail: error => {
        wx.hideLoading();
        console.error('下载失败:', error);
        wx.showToast({ title: '下载失败', icon: 'none' });
      }
    });
  },
  // 复制链接
  onCopyUrl(e) {
    const item = e.currentTarget.dataset.item;
    if (!item.fileUrl) return wx.showToast({ title: '无链接', icon: 'none' });
    wx.setClipboardData({ 
      data: item.fileUrl, 
      success: () => wx.showToast({ title: '已复制', icon: 'success' }) 
    });
  },
  // 删除记录
  onDelete(e) {
    const item = e.currentTarget.dataset.item;
    wx.showModal({
      title: '确认删除',
      content: '请确定是否删除数据',
      confirmColor: '#d32f2f',
      success: async res => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...', mask: true });
            await financeExport.exportDelete(item.id);
            wx.hideLoading();
            wx.showToast({ title: '删除成功', icon: 'success' });
            // 刷新当前页面
            this.setData({ pageNum: 1 }, () => {
              this.loadList(true);
            });
          } catch (error) {
            wx.hideLoading();
            console.error('删除失败:', error);
            wx.showToast({ 
              title: (error && error.data && error.data.msg) || '删除失败', 
              icon: 'none' 
            });
          }
        }
      }
    });
  },
  // 测试方法：手动触发加载更多
  testLoadMore() {
    console.log('Manual test load more');
    this.onLoadMore();
  },
  
  // 调试方法：打印当前状态
  debugStatus() {
    console.log('Current status:', {
      exportListLength: this.data.exportList.length,
      pageNum: this.data.pageNum,
      hasMore: this.data.hasMore,
      loading: this.data.loading,
      pageSize: this.data.pageSize
    });
  },
  
  // 手动触发下一页（用于测试）
  manualNextPage() {
    console.log('Manual next page triggered');
    if (this.data.loading) {
      console.log('Currently loading, skipping...');
      return;
    }
    if (!this.data.hasMore) {
      console.log('No more data, hasMore is false');
      return;
    }
    this.onLoadMore();
  },
}) 